/*
 * @description: 
 * @Author: Islands
 * @Date: 2024-06-14 20:28:05
 * @LastEditTime: 2024-06-21 16:11:43
 */
import type { App, Component } from "vue";



type EventShim = {
  new(...args: any[]): {
    $props: {
      onClick?: (...args: any[]) => void;
    };
  };
};

export type WithInstall<T> = T & {
  install(app: App): void;
} & EventShim;

export type CustomComponent = Component & { displayName?: string };

export const withInstall = <T extends CustomComponent>(component: T, alias?: string) => {
  (component as Record<string, unknown>).install = (app: App) => {
    const compName = component.name || component.displayName;
    if (!compName) return;
    app.component(compName, component);
    if (alias) {
      app.config.globalProperties[alias] = component;
    }
  };
  return component as WithInstall<T>;
};





/**
 * 判断是否为外部链接
 * @param path 路由地址
 * @returns 
 */
export const isExternal = (path: string) => {
  const isExternal = /^(https?:|http?:|mailto:|tel:)/.test(path);
  return isExternal;
};


/**
 * 解析rgba格式
 * @param color 
 * @returns 
 */
export function toRgba(color: string, opacity?: any): string {
  // 移除字符串中的所有空格
  const trimmedColor = color.replace(/\s+/g, '');
  // 尝试解析十六进制颜色
  if (trimmedColor[0] === '#') {
    const r = parseInt(trimmedColor.slice(1, 3), 16);
    const g = parseInt(trimmedColor.slice(3, 5), 16);
    const b = parseInt(trimmedColor.slice(5, 7), 16);
    if(opacity!=undefined){
      return `rgba(${r},${g},${b},${opacity})`;
    }
    return `rgba(${r},${g},${b},1)`;
  }
  // 尝试解析RGB颜色
  const rgbMatch = trimmedColor.match(/^rgb\((\d+),(\d+),(\d+)\)$/);  
  if (rgbMatch) {
    if (opacity != undefined) {
      return `rgba(${rgbMatch[1]},${rgbMatch[2]},${rgbMatch[3]},,${parseFloat(opacity)})`;
    }
    return `rgba(${rgbMatch[1]},${rgbMatch[2]},${rgbMatch[3]},1)`;
  }
  // 尝试解析RGBA颜色
  const rgbaMatch = trimmedColor.match(/^rgba\((\d+),(\d+),(\d+),(\d*\.\d+|\d+)\)$/);
  if (rgbaMatch) {
    if (opacity != undefined) {
      return `rgba(${rgbaMatch[1]},${rgbaMatch[2]},${rgbaMatch[3]},${parseFloat(opacity)})`;
    }
    return `rgba(${rgbaMatch[1]},${rgbaMatch[2]},${rgbaMatch[3]},${parseFloat(rgbaMatch[4])})`;
  }
  // 不能识别的颜色格式
  return 'rgba(0, 206, 209, 1)';
}
